﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace LianKe.BaseData
{
    public class XmlToDictionaryConverter
    {
        public Dictionary<string, object> Convert(string xmlString)
        {
            // 清理XML格式（处理用户示例中的异常空格）
            var cleanedXml = xmlString
                .Replace(" < ", "<")
                .Replace(" > ", ">")
                .Replace(" <", "<")
                .Replace("> ", ">");

            var doc = XDocument.Parse(cleanedXml);
            var root = doc.Root;

            return ParseNode(root);
        }

        private Dictionary<string, object> ParseNode(XElement element)
        {
            var dict = new Dictionary<string, object>();

            foreach (var node in element.Elements())
            {
                // 处理叶子节点
                if (!node.HasElements)
                {
                    dict[node.Name.LocalName] = node.Value.Trim();
                }
                // 处理嵌套节点（示例XML中不存在，但保留扩展性）
                else
                {
                    dict[node.Name.LocalName] = ParseNode(node);
                }
            }
            return dict;
        }
    }
}
